﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.BLL.DicBll;
using Lenovo.CFI.BLL.DicMgr;
using Lenovo.CFI.Common;
using Lenovo.CFI.Common.Dic;
using Lenovo.CFI.Web.Helper;

namespace Lenovo.CFI.Web.VP
{
    public partial class DcList : System.Web.UI.UserControl
    {
        IdeaBl ideaBl = new IdeaBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TopicBl topicBl = new TopicBl();
                List<Topic> topics = topicBl.GetTopic();
                Dictionary<int, List<string>> dcTypes = null;
                topicBl.GetDcTopic(UserHelper.UserName, out dcTypes);
                topics = topics.FindAll(t => dcTypes.ContainsKey(t.ID) && t.Status != TopicStatus.Create);        // 可以访问的

                this.DdlTopic.DataSource = topics;
                this.DdlTopic.DataTextField = "Title";
                this.DdlTopic.DataValueField = "ID";
                this.DdlTopic.DataBind();

                this.DdlStatus.Enabled = false;

                BindHelper.BindNextAction(this.DdlSuggestion, "Select...", "-1", null, false);
                BindHelper.BindOtherBu(this.DdlOtherBU, "Select...", "-1", null, false);
                BindHelper.BindKeyword(this.DdlKeyword1, "Select...", "-1", null, false);
                BindHelper.BindKeyword(this.DdlKeyword2, "Select...", "-1", null, false);
                BindHelper.BindKeyword(this.DdlKeyword3, "Select...", "-1", null, false);


                if (topics.Count > 0)
                {
                    selectedTopic = topics[0];
                    ViewState["topicid"] = selectedTopic.ID;
                    ViewState["status"] = -1;

                    this.BindData();
                }
                    
                MessageHelper.Prepare(this.Page);
            }
        }


        protected void DdlTopic_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["topicid"] = Convert.ToInt32(this.DdlTopic.SelectedValue);

            this.BindData();
        }

        protected void DdlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["status"] = Convert.ToInt32(this.DdlStatus.SelectedValue);

            this.BindData();

        }

        Topic selectedTopic = null;
        bool showOpinion = false;
        bool showSuggestion = false;
        Dictionary<int, Idea> ideasDic = null;
        private void BindData()
        {
            int topicID = (int)ViewState["topicid"];

            if (selectedTopic == null) selectedTopic = new TopicBl().GetTopicByID(topicID);

            if (selectedTopic.Status == TopicStatus.Start)
            {
                showOpinion = true;
            }
            else
            {
                if (selectedTopic.Status == TopicStatus.Suggestion || 
                    selectedTopic.Status == TopicStatus.Execution || 
                    selectedTopic.Status == TopicStatus.Closed)
                {
                    showSuggestion = true;
                }
            }

            if ((int)selectedTopic.Status >= 1 && (int)selectedTopic.Status <= 5)
            {
                List<string> types = new TopicBl().GetDcTypes(UserHelper.UserName, selectedTopic.ID);

                this.DdlStatus.Enabled = false;

                this.GvList.DataSource = new IdeaBl().GetIdeaForDC(selectedTopic.ID, types);    // 申请类型
                this.GvList.DataBind();
            }
            else if ((int)selectedTopic.Status >= 6 && (int)selectedTopic.Status <= 8)
            {                
                List<string> types = new TopicBl().GetDcTypes(UserHelper.UserName, selectedTopic.ID);

                this.DdlStatus.Enabled = true;

                List<IdeaReview> reviews = new ReviewBl().GetReview(topicID).FindAll(r => types.Contains(r.ReviewType));    // TODO:根据DCOwner也可以

                int status = (int)ViewState["status"];
                if (status != -1) reviews = reviews.FindAll(r => r.DcConfirmed == (SuggestionStatus)status);

                ideasDic = new Dictionary<int, Idea>();
                foreach (Idea idea in new IdeaBl().GetIdeaByReviews(reviews)) ideasDic.Add(idea.ID, idea);

                reviews.Sort((x, y) => y.ReviewScore.CompareTo(x.ReviewScore));

                this.GvList.DataSource = reviews;
                this.GvList.DataBind();
            }
        }


        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);

                if (e.Row.DataItem is Idea)
                {
                    Idea idea = (Idea)e.Row.DataItem;

                    ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                        UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                    ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;
                    ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(idea.Type).Title;

                    if (showOpinion && (idea.Status == IdeaStatus.Submitted || idea.Status == IdeaStatus.Agree))
                    {
                        ((LinkButton)e.Row.FindControl("BtnOpinion")).Visible = true;
                    }
                    else
                    {
                        ((LinkButton)e.Row.FindControl("BtnOpinion")).Visible = false;
                    }

                    ((LinkButton)e.Row.FindControl("BtnSuggestion")).Visible = false;

                }
                else
                {
                    IdeaReview review = (IdeaReview)e.Row.DataItem;
                    Idea idea = ideasDic[review.IdeaID];

                    ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                        UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                    ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;
                    ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(review.ReviewType).Title;
                    ((Literal)e.Row.FindControl("LtrScore")).Text = review.ReviewScore.ToString("f2");


                    if (showSuggestion && (idea.Status == IdeaStatus.Suggestion || idea.Status == IdeaStatus.Execution))
                    {
                        ((LinkButton)e.Row.FindControl("BtnSuggestion")).Visible = true;
                    }
                    else
                    {
                        ((LinkButton)e.Row.FindControl("BtnSuggestion")).Visible = false;
                    }

                    ((LinkButton)e.Row.FindControl("BtnOpinion")).Visible = false;
                }
            }
        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Opinion")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                ViewState["IdeaID"] = id;

                Idea idea = new IdeaBl().GetIdeaById(id);

                this.TxtOpinion.Text = idea.DcComment;
                this.CbAttend.Checked = (idea.DcAttendMeeting != false);

                this.MpeOpinion.Show();
            }
            else if (e.CommandName == "Suggestion")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                ViewState["ReviewID"] = id;

                IdeaReview review = new ReviewBl().GetReviewByID(id);
                Idea idea = new IdeaBl().GetIdeaById(review.IdeaID);

                this.DdlSuggestion.ClearSelection();
                ListItem item = this.DdlSuggestion.Items.FindByValue(review.NextAction);
                if (item != null) item.Selected = true;

                this.TxtSuggestionPrevious.Text = review.NextActionPrev != null ? NextActionDicMgr.GetByCode(review.NextActionPrev).Title : "";

                this.OuacExecutor.Text = review.ActionExecutor;

                this.DdlLevel.ClearSelection();
                item = this.DdlLevel.Items.FindByValue(idea.SecretLevel.ToString());
                if (item != null) item.Selected = true;

                this.DdlKeyword1.ClearSelection();
                if (idea.Keywords.List.Length > 0)
                {
                    item = this.DdlKeyword1.Items.FindByValue(idea.Keywords.List[0]);
                    if (item != null) item.Selected = true;
                }
                this.DdlKeyword2.ClearSelection();
                if (idea.Keywords.List.Length > 1)
                {
                    item = this.DdlKeyword2.Items.FindByValue(idea.Keywords.List[1]);
                    if (item != null) item.Selected = true;
                }
                this.DdlKeyword3.ClearSelection();
                if (idea.Keywords.List.Length > 2)
                {
                    item = this.DdlKeyword3.Items.FindByValue(idea.Keywords.List[2]);
                    if (item != null) item.Selected = true;
                }
                this.TxtFreeKeyword.Text = idea.FreewordsText;


                if (review.DcConfirmed == SuggestionStatus.None)
                {
                    this.BtnAgreeSuggestion.Enabled = true;
                    this.BtnRejectSuggestion.Enabled = true;
                    this.BtnFinishSuggestion.Enabled = true;
                    this.BtnMailSuggestion.Enabled = true;
                }
                else if (review.DcConfirmed == SuggestionStatus.OnGoing)
                {
                    this.BtnAgreeSuggestion.Enabled = true;
                    this.BtnRejectSuggestion.Enabled = true;
                    this.BtnFinishSuggestion.Enabled = true;
                    this.BtnMailSuggestion.Enabled = true;
                }
                else if (review.DcConfirmed == SuggestionStatus.Reject)
                {
                    this.BtnAgreeSuggestion.Enabled = false;
                    this.BtnRejectSuggestion.Enabled = false;
                    this.BtnFinishSuggestion.Enabled = false;
                    this.BtnMailSuggestion.Enabled = false;
                }
                else if (review.DcConfirmed == SuggestionStatus.Finished)
                {
                    this.BtnAgreeSuggestion.Enabled = false;
                    this.BtnRejectSuggestion.Enabled = false;
                    this.BtnFinishSuggestion.Enabled = false;
                    this.BtnMailSuggestion.Enabled = true;
                }

                this.MpeSuggestion.Show();
            }

        }

        protected void GvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GvList.PageIndex = e.NewPageIndex;
            this.BindData();
        }


        protected void BtnSaveOpinion_Click(object sender, EventArgs e)
        {
            try
            {
                new IdeaBl().DcComment((int)ViewState["IdeaID"], this.TxtOpinion.Text, this.CbAttend.Checked);

                MessageHelper.RegShowJSAjax(this.BtnSaveOpinion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSaveOpinion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnSaveOpinion, this.Page);
            }

            this.BindData();
        }

        protected void BtnAgreeSuggestion_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().DcSuggest((int)ViewState["ReviewID"], SuggestionStatus.OnGoing,
                    this.DdlSuggestion.SelectedIndex == 0 ? null : this.DdlSuggestion.SelectedValue,
                    this.DdlOtherBU.SelectedIndex == 0 ? null : this.DdlOtherBU.SelectedValue, 
                    this.OuacExecutor.Text, 
                    Convert.ToInt32(this.DdlLevel.SelectedValue),
                    this.DdlKeyword1.SelectedIndex == 0 ? null : this.DdlKeyword1.SelectedValue,
                    this.DdlKeyword2.SelectedIndex == 0 ? null : this.DdlKeyword2.SelectedValue,
                    this.DdlKeyword3.SelectedIndex == 0 ? null : this.DdlKeyword3.SelectedValue,
                    this.TxtFreeKeyword.Text.Trim());

                MessageHelper.RegShowJSAjax(this.BtnAgreeSuggestion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnAgreeSuggestion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnAgreeSuggestion, this.Page);
            }

            this.BindData();
        }

        protected void BtnRejectSuggestion_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().DcSuggest((int)ViewState["ReviewID"], SuggestionStatus.Reject, null, null, null, 1, null, null, null, null);

                MessageHelper.RegShowJSAjax(this.BtnRejectSuggestion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnRejectSuggestion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnRejectSuggestion, this.Page);
            }

            this.BindData();
        }

        protected void BtnFinishSuggestion_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().DcSuggest((int)ViewState["ReviewID"], SuggestionStatus.Finished,
                    this.DdlSuggestion.SelectedIndex == 0 ? null : this.DdlSuggestion.SelectedValue,
                    this.DdlOtherBU.SelectedIndex == 0 ? null : this.DdlOtherBU.SelectedValue,
                    this.OuacExecutor.Text,
                    Convert.ToInt32(this.DdlLevel.SelectedValue),
                    this.DdlKeyword1.SelectedIndex == 0 ? null : this.DdlKeyword1.SelectedValue,
                    this.DdlKeyword2.SelectedIndex == 0 ? null : this.DdlKeyword2.SelectedValue,
                    this.DdlKeyword3.SelectedIndex == 0 ? null : this.DdlKeyword3.SelectedValue,
                    this.TxtFreeKeyword.Text.Trim());

                MessageHelper.RegShowJSAjax(this.BtnFinishSuggestion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnFinishSuggestion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnFinishSuggestion, this.Page);
            }

            this.BindData();
        }

        protected void BtnMailSuggestion_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().DcNoticeMail((int)ViewState["ReviewID"], null);

                MessageHelper.RegShowJSAjax(this.BtnMailSuggestion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnMailSuggestion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnMailSuggestion, this.Page);
            }

            this.BindData();
        }

        
    }
}